TOOL.Category = "Turret Weaons"
TOOL.Name = "Cannon Turret"
TOOL.Command = nil
TOOL.ConfigName = ""
TOOL.ent = {} 
TOOL.ClientConVar["Power"] = "10"
cleanup.Register( "cannonturret" )

if CLIENT then
   language.Add ("Tool_cannonturret_name", "Cannon Turret")
   language.Add ("Tool_cannonturret_desc", "A customizable Cannon Turret.")
   language.Add ("Tool_cannonturret_0", "Primary: Spawn a Cannon Turret")
   language.Add ("Undone_cannonturret", "Cannon Turret undone.")
end



function TOOL:LeftClick( trace )
	if (CLIENT) then return true end
	
		
	if ( !trace.Hit ) then return end
	local ply = self:GetOwner()
	local Ang = (trace.HitNormal:Angle() + Angle(90,0,0))
	local Pos = trace.HitPos + trace.HitNormal* 8
	if ( SERVER and !util.IsValidPhysicsObject( trace.Entity, trace.PhysicsBone ) ) then return false end

	   local Power = self:GetClientNumber("power")

	local Weapon = MakeCannon(ply, Pos, Ang, Power)
	
	local phys = Weapon:GetPhysicsObject()  	
	if (phys:IsValid()) then  		
		local weld = constraint.Weld(Weapon, trace.Entity, 0, trace.PhysicsBone, 0)
		local nocollide = constraint.NoCollide(Weapon, trace.Entity, 0, trace.PhysicsBone)
		undo.Create("cannonturret")
		undo.AddEntity( Weapon )
		undo.AddEntity( weld )
		undo.AddEntity( nocollide )
		undo.SetPlayer( ply )
	undo.Finish()
	end 
	
	
   return true
end

function TOOL:RightClick( trace )
	if (CLIENT) then return true end
	local ply = self:GetOwner()
	
	if ( !trace.Hit ) then return end
	local Ang = (trace.HitNormal:Angle() + Angle(90,0,0))
	local Pos = trace.HitPos + trace.HitNormal* 8
	
	if ( SERVER and !util.IsValidPhysicsObject( trace.Entity, trace.PhysicsBone ) ) then return false end

	   local Power = self:GetClientNumber("power")

	local Weapon = MakeCannon(ply, Pos, Ang, Power)
	
	
	undo.Create("cannonturret")
		undo.AddEntity( Weapon )
		undo.SetPlayer( ply )
	undo.Finish()
	
   return true
end



if (SERVER) then

	 function MakeCannon(pl, Pos, Ang, Pow)
		
		
	
	local turretcannon = ents.Create("turretcannon")
    turretcannon:SetPos(Pos)
	turretcannon:SetAngles( Ang)
	turretcannon:Spawn()
    turretcannon:Activate()
    turretcannon:Setup(Pow)
	
	local ttable = {
					Pow = Pow;
						}
		table.Merge(turretcannon:GetTable(), ttable )
	
	return turretcannon
	end
duplicator.RegisterEntityClass("turretcannon", MakeCannon, "Pos", "Ang", "Pow", "frozen")
end

if CLIENT then
function TOOL.BuildCPanel(panel)
   
   panel:AddControl("Header", {Text = "#Tool_cannonturret_name", Description = "#Tool_cannonturret_desc"})

   panel:AddControl("Slider", {
      Label = "Power",
      Type = "Integer",
      Min = "10",
      Max = "200",
      Command = "cannonturret_Power"})

end 
end 